# -*- coding: utf-8 -*-

import os
import sys
import time
import datetime
import subprocess


class LogFilter:

    def __init__(self):
        pass

    def _timeStr(self):
        return datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S.%f] ')

    def _filter(self, line):
        line = line.rstrip()
        if not line:
            return
        if -1 != line.find("DebugBindings.gen.cpp Line: 51)"):
            return None
        if line.endswith("I Unity   :  "):
            return None
        return line

    def proc(self, line):
        line_f = self._filter(line)
        if line_f is None:
            return None
        return self._timeStr() + line_f


def rt_run(cmd, write_file="", is_append_file=True, line_proc=None):
    print("Execute: {}".format(cmd))
    import sys
    import subprocess
    f = None
    if write_file != "":
        if not isinstance(write_file, (str, unicode)):
            f = write_file
        else:
            try:
                f = open(write_file, 'a' if is_append_file else 'w')
            except IOError:
                print("@@@@ Can not open file {}".format(write_file))

    lines = []
    try:
        pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, stderr=subprocess.STDOUT)
        for line in iter(pipe.stdout.readline, ''):
            lines.append(line)
            if line_proc is None:
                sys.stdout.write(line)
            else:
                line_proc(line)

            if f is not None:
                try:
                    f.write(line)
                except IOError:
                    pass

    finally:
        if f is not None and isinstance(write_file, (str, unicode)):
            f.close()

def test1():
    f = LogFilter()
    while True:
        line = sys.stdin.readline()
        line = f.proc(line)
        if line is not None:
            sys.stdout.write(line)
            sys.stdout.flush()
			
def test2():
    c = rt_run("ping 127.0.0.1", 'haha.log', True)
    print "--------------------------"
    print c
    print "\n".join(c)


def main():
    cmd = 'ping 127.0.0.1'
    cmd = 'adb_server.exe logcat -v raw -s Unity'
    logf = LogFilter()
    f = open("ClientLog.txt", "w")
    pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE)
    #while True:
    #    line = pipe.stdout.readline()
    #    print line
    #    time.sleep(0.2)
    #pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    # pipe = subprocess.Popen(, stdout=subprocess.PIPE)
    for line in iter(pipe.stdout.readline, ''):
        #print line
        line = logf.proc(line)
        if line is not None:
            print(line)
            try:
                f.write(line + "\n")
            except:
                pass


if __name__ == '__main__':
    main()

